package cn.fl.warrant.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.filechooser.FileSystemView;

import net.sf.json.JSONArray;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import tc.esign.facade.esign.api.IFilSignApiService;
import tc.esign.facade.esign.condition.FilSignQueryCondition;
import tc.esign.facade.esign.dto.FilSignDTO;
import cmm.comm.facade.flow.dto.SysFlowRejRsnDTO;
import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.framework.dto.SysDictionaryDTO;
import cmm.comm.facade.upload.condition.SysUlFilesRecQueryCondition;
import cmm.comm.facade.upload.constant.SysUlFilesRecConstant;
import cmm.comm.facade.upload.dto.SysUlFilesRecDTO;
import cmm.mid.core.framework.dto.BaseDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.ass.service.IAssDealCarService;
import cn.fl.ass.service.IAssDealRecAmtService;
import cn.fl.ass.service.IAssDealRedeemService;
import cn.fl.ass.service.IAssDealSellService;
import cn.fl.ass.service.IAssParkingValidService;
import cn.fl.ass.service.IAssTrailCarDService;
import cn.fl.ass.service.IAssTrailCarHvService;
import cn.fl.ass.service.IAssTrailCarMService;
import cn.fl.audit.constant.ExportBookConstant;
import cn.fl.car300.constant.InfCar300RecConstant;
import cn.fl.customer.service.ICstBscInfoService;
import cn.fl.customer.vo.CstBscInfoVO;
import cn.fl.esign.service.IFilSignService;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.project.api.IProjectQueryApiService;
import cn.fl.project.condition.PrjBscInfoQueryCondition;
import cn.fl.project.condition.PrjContCfgDQC;
import cn.fl.project.dto.PrjContCfgDDTO;
import cn.fl.project.service.IPrjBscInfoService;
import cn.fl.project.vo.PrjBscInfoVO;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.system.service.ISysOrgService;
import cn.fl.system.service.ISysUlFilesRecService;
import cn.fl.system.service.ISysUsrService;
import cn.fl.system.transform.SysUlFilesRecVOTransform;
import cn.fl.system.vo.SysOrgVO;
import cn.fl.system.vo.SysUlFilesRecVO;
import cn.fl.upload.constant.UploadConstant;
import cn.fl.warrant.service.IArcBorrowMainService;
import cn.fl.warrant.service.IArcBscInfoService;
import cn.fl.warrant.service.IArcMgrMainService;
import cn.fl.warrant.service.IArcReceiptMainService;
import cn.fl.warrant.service.IWarrantFileManageMService;
import cn.fl.warrant.transform.ArcBscInfoVOTransform;
import cn.fl.warrant.transform.ArcMgrDetailVOTransform;
import cn.fl.warrant.transform.ArcMgrMainVOTransform;
import cn.fl.warrant.transform.ArcReceiptDetailVOTransform;
import cn.fl.warrant.vo.ArcBscInfoVO;
import cn.fl.warrant.vo.ArcMgrDetailVO;
import cn.fl.warrant.vo.ArcMgrMainVO;
import cn.fl.warrant.vo.WarrantFileManageVO;

import com.alibaba.fastjson.JSONObject;

import fl.constant.facade.framework.constant.WarrantConstant;
import fl.flow.facade.flow.constant.FlowConstant;
import fl.riskctrl.facade.riskctrl.api.IRiskCtrlSearchApiService;
import fl.riskctrl.facade.riskctrl.condition.RcCstBscInfoQC;
import fl.riskctrl.facade.riskctrl.dto.RcCstBscInfoDTO;
import fl.warrant.facade.archive.condition.ArcMgrDetailQC;
import fl.warrant.facade.archive.condition.ArcMgrMainQC;
import fl.warrant.facade.archive.condition.WarrantFileManageQueryCondition;
import fl.warrant.facade.archive.constant.ArchiveConstants;
import fl.warrant.facade.archive.dto.ArcMgrDetailDTO;
import fl.warrant.facade.archive.dto.ArcMgrMainDTO;

/**
 * @Description: 权证档案管理
 */
@Controller
@RequestMapping("/warrant/warrantfilemanage")
public class WarrantFileManageController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(WarrantFileManageController.class);
	
	/**
	 * SysUlFilesRec 服务层BEAN
	 */
	@Autowired
	private ISysUlFilesRecService sysUlFilesRecService;
	
	/**
	 *ISysUsrService 服务层BEAN
	 */
	@Autowired
	private ISysUsrService sysUsrService;
	
	@Autowired
	private IArcMgrMainService arcMgrMainService;
	/**
	 * 数据字典服务
	 */
	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;
	/**
     * 项目基础服务
     */
    @Autowired
    private IPrjBscInfoService prjBscInfoService;
    /**
	 * 档案管理服务
	 */
	@Autowired
	private IWarrantFileManageMService warrantFileManageMService;
	
	/**
	 * 客户基础信息表
	 */
	@Autowired
	private ICstBscInfoService cstBscInfoService;
	
	/**
	 * 组织架构表 客户端服务层接口
	 */
	@Autowired
	private ISysOrgService sysOrgService;
	
	/**
	 * ArcBscInfo 服务层BEAN
	 */
	@Autowired
	private IArcBscInfoService arcBscInfoService;

	/**
	 * FilSign 服务层BEAN
	 */
	@Autowired
	private IFilSignService filSignService;
	
	@Autowired
	private IArcReceiptMainService arcReceiptMainService;
	
	@Autowired
	private IProjectQueryApiService projectQueryApiService;
	@Autowired
	private IFilSignApiService filSignApiService;
	@Autowired
	private IArcBorrowMainService arcBorrowMainService;//借阅主表

	@Autowired
	private IRiskCtrlSearchApiService riskCtrlSearchApiService;
	/**
	 * 档案管理列表页面
	 */
	@RequestMapping("/toListPage.do")
	public String toListPage(HttpServletRequest request) {
		String sysCd = CurrentThreadContext.getCurrentSysCd(); 
		String orgCd = CurrentThreadContext.getCurrentOrgCd();
		
		
		//获取归档状态
		String archiveState = PropertiesCacheUtils.getProperty(WarrantConstant.ARCHIVE_STATE);
		request.setAttribute("archiveStateList", warrantFileManageMService.getKvList(sysCd, orgCd,archiveState));
		
		//业务类型
		List<KeyValueVO> bizTypeList = prjBscInfoService.getBizTypeList();
		request.setAttribute("bizTypeList", bizTypeList);
		
		//支付表状态
		request.setAttribute("prdStsCdList", prjBscInfoService.getPrdStsCdList());
  		
		BaseLogUtils.info(logger, "toListPage", "跳转到档案管理列表页面.", CurrentThreadContext.getCurrentUserName());
		return "warrant/warrantFileManage/fileManageManager";
	}

	
	/**
	 * 初始化档案管理列表
	 */
	@RequestMapping("/initList.do")
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		WarrantFileManageQueryCondition qc = this.initTrailParam(request, response);
		qc.setUsrId(CurrentThreadContext.getCurrentUserId());
		qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
		page.setCondition(qc);
		
		
//		Pager pager = this.warrantFileManageMService.searchListPage(page);
//		List<WarrantFileManageVO> list = (List<WarrantFileManageVO>) pager.getResultList();
//		ListPageVO<WarrantFileManageVO> listPage = new ListPageVO<WarrantFileManageVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initList", "查询档案管理列表数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return null;
	}
	
	@RequestMapping(value = "/toApplyPage.do")
	public ModelAndView toApplyPage(WarrantFileManageVO warrantFileManageVO ,HttpServletRequest request, HttpServletResponse response)  {
		
		request.setAttribute("warrantFileManageVO", warrantFileManageVO);
		//获取页面参数：支付表ID和支付表号
		String paySchId = request.getParameter("paySchId");
		String paySchNo = request.getParameter("paySchNo");
		String prjPrdDtlId = request.getParameter("prjPrdDtlId");
		String prjId = request.getParameter("prjId");
		String businessType = request.getParameter("businessType");
		String prjTypCd = request.getParameter("prjTypCd");
		String prjNm = request.getParameter("prjNm");
		String orgName = request.getParameter("orgName");
		String cstId = request.getParameter("cstId");
		String cstNm = request.getParameter("cstNm");
		ModelAndView view = new ModelAndView("warrant/warrantFileManage/warrantFileManageApply");
		view.addObject("paySchId", paySchId);
		view.addObject("paySchNo", paySchNo);
		view.addObject("prjPrdDtlId", prjPrdDtlId);//项目产品明细表ID
		view.addObject("prjId", prjId);
		view.addObject("businessType", businessType);
		view.addObject("prjTypCd", prjTypCd);//项目类型
		view.addObject("prjNm", prjNm);
		view.addObject("orgName", orgName);//事业部名称
		view.addObject("cstId", cstId);
		view.addObject("cstNm", cstNm);//客户名称
		view.addObject("sysDate", DateUtils.formatDateToString(new Date(), DateUtils.YYYY_MM_DD));
		view.addObject("applyNm", CurrentThreadContext.getCurrentUserName());
		
		BaseLogUtils.info(logger, "toApplyPage", "跳转到归档申请页面.[paySchId="+paySchId+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}
	
	
	/**
	 * 新增归档管理主表数据
	 * 同时发起归档申请流程
	 */
	@RequestMapping(value = "/apply.do")
	@ResponseBody
	public Object apply(WarrantFileManageVO warrantFileManageVO,HttpServletRequest request, HttpServletResponse response) throws BaseException {
		
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		
		
		//判断支付表ID是否为空
		if(StringUtils.isEmpty(warrantFileManageVO.getPaySchId())){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.error(logger, "getTrailCarApplyInfo", "获取数据,支付表主键不存在", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		try {
			
			/*if(StringUtils.isNotEmpty(warrantFileManageVO.getEnterTm())){
				entity.setBackDt(DateUtils.formatStringToDate(backDt, DateUtils.YYYY_MM_DD));
			}
			if(StringUtils.isNotEmpty(backPrice)){//元转分
				entity.setBackPrice(DecimalUtils.convertYuanToFen(Double.valueOf(backPrice)));
			}*/
		
			warrantFileManageVO.setArchiveState("1");
			warrantFileManageVO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			warrantFileManageVO.setCrtTm(new Date());
			warrantFileManageVO.setIsDel(BaseConstant.IS_YESNO_NO);
			warrantFileManageVO.setApplyNm(CurrentThreadContext.getCurrentUserName());
			warrantFileManageVO.setApplyId(CurrentThreadContext.getCurrentUserId());
			
		/*	//根据支付表ID获取拖车基本信息
			List<Long> ids = new ArrayList<Long>();
			ids.add(Long.valueOf(warrantFileManageVO.getPaySchId()));
			List<AssTrailCarDVO> details = this.assTrailCarDService.selectByPaySchId(ids);
			if(null == details){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "add", "获取数据,数据不存在.[paySchId="+warrantFileManageVO.getPaySchId()+"]", CurrentThreadContext.getCurrentUserName());
				return result;
			}else{
				if(details.size() > 0 && null != details.get(0)){
					BaseLogUtils.info(logger, "add", "拖车申请支付表号："+details.get(0).getPaySchNo());
					map.put("orgCode",details.get(0).getOrgSimpleCode());//事业部简称
					if(StringUtils.isNotEmpty(isOnline)){//GPS在线状态
						details.get(0).setIsOnline(Integer.parseInt(isOnline));
					}
				}
				//设置详细实体信息
				warrantFileManageVO.setDetails(AssTrailCarDVOTransform.toDTOList(details));
			}*/
			
			//保存归档管理主表和明细
			Long id = warrantFileManageMService.addWarrantFileManage(warrantFileManageVO);
			
			//设置流程参数
			WarrantFileManageQueryCondition qc = new WarrantFileManageQueryCondition();
			
			qc.setFlowModelType(FlowConstant.FLOW_MODEL_TYP_ASS_APPROVAL);//"017"拖车审批
			qc.setId(id);//主表ID
			qc.setOrgName(warrantFileManageVO.getOrgName());//项目所属事业部名称
			qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
			qc.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
			qc.setBuOrgCd(CurrentThreadContext.getCurrentBuOrgCd());//当前登录人事业部代码
			qc.setUsrId(CurrentThreadContext.getCurrentUserId());
			qc.setUsrNm(CurrentThreadContext.getCurrentUserName());
			qc.setCstId(warrantFileManageVO.getCstId());
			qc.setCstNm(warrantFileManageVO.getCstNm());
			qc.setPrjId(warrantFileManageVO.getPrjId());//项目基础信息表ID
			qc.setPrjPrdDtlId(warrantFileManageVO.getPrjPrdDtlId());//项目产品明细表ID
			qc.setPrjTypCd(warrantFileManageVO.getPrjTypCd());
			qc.setPrjNm(warrantFileManageVO.getPrjNm());
			qc.setBusinessType(warrantFileManageVO.getBusinessType());
			
			Map<String,Object> map = new HashMap<String,Object>();
			qc.setFlow_Map(map);//附加参数
			
			//发起流程
//			result = this.assTrailCarMService.addTrailCarApply(qc);
			result = this.warrantFileManageMService.startFlow(qc);
			
			result.setData(id);
			BaseLogUtils.info(logger, "add", "新增归档管理主表数据.[id="+id+"] DATA:" + JSONObject.toJSONString(warrantFileManageVO), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增归档管理主表数据失败1.DATA:" + JSONObject.toJSONString(warrantFileManageVO) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "新增归档管理主表数据失败2.DATA:" + JSONObject.toJSONString(warrantFileManageVO) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}
	
	/**
	 * 初始化拖车管理列表-获取查询参数
	 */
	public WarrantFileManageQueryCondition initTrailParam(HttpServletRequest request, HttpServletResponse response) {
		//获取页面参数-共同参数
		String cstNm = request.getParameter("cstNm");
		String contNo = request.getParameter("contNo");
		String paySchNo = request.getParameter("paySchNo");
		//拖车管理-查询特有参数
		String minBackDay = request.getParameter("minBackDay");
		String maxBackDay = request.getParameter("maxBackDay");
		String beginBackDate = request.getParameter("beginBackDate");
		String endBackDate = request.getParameter("endBackDate");
		String dealStsCd = request.getParameter("dealStsCd");
		//拖车申请--查询特有参数
		String minDay = request.getParameter("minOverdueDay");
		String maxDay = request.getParameter("maxOverdueDay");
		String backStsCd = request.getParameter("backStsCd");
		//选中行的支付表idList集合
		String pkIds = request.getParameter("pkIds");
		
		WarrantFileManageQueryCondition qc = new WarrantFileManageQueryCondition();
		if (StringUtils.isNotEmpty(cstNm)) {//客户名称
			qc.setCstNm(cstNm);
		}
		if (StringUtils.isNotEmpty(contNo)) {//合同号
			qc.setContNo(contNo);
		}
		if (StringUtils.isNotEmpty(paySchNo)) {//支付表号
			qc.setPaySchNo(paySchNo);
		}
		if (StringUtils.isNotEmpty(minBackDay)) {//拖回天数-最小值
			qc.setMinBackDay(Integer.parseInt(minBackDay));
		}
		if (StringUtils.isNotEmpty(maxBackDay)) {//拖回天数-最大值
			qc.setMaxBackDay(Integer.parseInt(maxBackDay));
		}
		if (StringUtils.isNotEmpty(beginBackDate)) {//拖回日期-开始
			qc.setBeginBackDate(DateUtils.formatStringToDate(beginBackDate, DateUtils.YYYY_MM_DD));
		}
		if (StringUtils.isNotEmpty(endBackDate)) {//拖回日期-结束
			qc.setEndBackDate(DateUtils.formatStringToDate(endBackDate, DateUtils.YYYY_MM_DD));
		}
		if (StringUtils.isNotEmpty(dealStsCd)) {//处置状态
			qc.setDealStsCd(dealStsCd);
		}
		if (StringUtils.isNotEmpty(minDay)) {//逾期天数-最小值
			Long minOverdueDay = Long.parseLong(minDay);
			qc.setMinOverdueDay(minOverdueDay);
		}
		if (StringUtils.isNotEmpty(maxDay)) {//逾期天数-最大值
			Long maxOverdueDay = Long.parseLong(maxDay);
			qc.setMaxOverdueDay(maxOverdueDay);
		}
		if (StringUtils.isNotEmpty(backStsCd)) {//拖车状态
			qc.setBackStsCd(backStsCd);
		}
		//要导出的拖车信息关联的支付表idList集合
		if(StringUtils.isNotEmpty(pkIds)){
			List<String> pkIdsList = new ArrayList<String>();
			JSONArray pkIdsArray = JSONArray.fromObject(pkIds);
			for (Object object : pkIdsArray) {
				pkIdsList.add(object.toString());
			}
			qc.setPkIdsList(pkIdsList);
		}
		return qc;
	}
	
	
	/**
	 * 到拖车申请流程附加信息页面
	 */
	@RequestMapping(value = "/toViewPage.do")
	public ModelAndView toViewPage(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		//获取流程传过来的参数
		String tcMasterId = request.getParameter("tcMasterId");
		String proIntId = request.getParameter("processInstanceId");//流程实例ID
		String sysCd = CurrentThreadContext.getCurrentSysCd(); 
		String orgCd = CurrentThreadContext.getCurrentOrgCd();
		String flag = request.getParameter("flag");
		ModelAndView view = new ModelAndView("warrant/warrantFileManage/warrantFileManageView");
		/*//处置接收人类型
		List<KeyValueVO> backFlagList = this.assTrailCarMService.getKvList(InterfaceConstants.BACK_FLAG_CD, sysCd, orgCd);
		view.addObject("backFlagList", backFlagList);
		view.addObject("tcMasterId", tcMasterId);
		view.addObject("proIntId", proIntId);		
		view.addObject("flag", flag);
		view.addObject("sysDate", DateUtils.formatDateToString(new Date(), DateUtils.YYYY_MM_DD));
		view.addObject("loginUsrNm", CurrentThreadContext.getCurrentUserName());*/
		return view;
	}
	
	/**
	 * 档案资料下载页
	 * zhangrongcong 20180201
	 */
	@RequestMapping(value = "/toArchiveDownload.do")
	public ModelAndView toArchiveDownload(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		ModelAndView view = new ModelAndView("archive/warrantFileManage/warrantArchiveDownload");
		//事业部
		List<KeyValueVO> orgList = this.cstBscInfoService
						.searchBusinessOrgList();
		request.setAttribute("buOrgCdList", orgList);
		//省公司
		request.setAttribute("prList", arcMgrMainService.getPrList());
		System.out.println("档案资料下载方法");
		return view;
	}
	/**
	 * 上传excel并解析资产包中支付表号
	 * @param upfile
	 * @param request
	 * zhangrongcong
	 * @throws IOException
	 */
	@RequestMapping(value = "/importExcel.do",method = { RequestMethod.POST, RequestMethod.GET})  
    @ResponseBody  
    public Object importExcel( @RequestParam(value = "upfile") MultipartFile upfile,HttpServletRequest request) throws IOException{  
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "读取数据成功");
		if (null == upfile) { 
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("模板文件为空,请选择文件");
			BaseLogUtils.info(logger, "addFlowStart", SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY, CurrentThreadContext.getCurrentUserName());
			return result; 
     
        }
		String fileName = upfile.getOriginalFilename();//report.xls 
        String[] names=fileName.split("\\.");
        if(!names[names.length-1].toLowerCase().equals("xls") && !names[names.length-1].toLowerCase().equals("xlsx")){
        	result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("上传文件必须是 xls 或者 xlsx");
			BaseLogUtils.info(logger, "addFlowStart", SysLogConstant.LOG_CMM_ENABLE_FAIL, CurrentThreadContext.getCurrentUserName());
			return result; 
        }
        InputStream fis = upfile.getInputStream();  
        
        result = this.parseExcel(fis,result);  
        //解析到的数据就可以做一些数据库的插入操作了……  
        HttpSession session = request.getSession();
        session.removeAttribute("paySchCds");
        session.setAttribute("paySchCds", result.getData());
//        System.out.println(session);
//        System.out.println(result);
       return result;
	}
	
	/**
	 * 解析读取excel里的内容
	 * @param fis
	 * @param result
	 * @return
	 * zhangrongcong
	 */
	public DataResultVO parseExcel(InputStream fis,DataResultVO result) {
		String paySchCds = "";
		List<String> arr = new ArrayList<>();
		try {  
            HSSFWorkbook book = new HSSFWorkbook(fis);  
            HSSFSheet sheet = book.getSheetAt(0);
            int firstRow = sheet.getFirstRowNum();
            int lastRow = sheet.getLastRowNum();
            int num = 0;
            for(int i = firstRow; i < lastRow + 1; i++) {
            	HSSFCell cell = sheet.getRow(i).getCell(0) ;
            	if(cell.getStringCellValue() != null && !("").equals(cell.getStringCellValue())){
            		if(num == 999){
            			arr.add(paySchCds);
            			paySchCds = "";
            			num = 0;
            		}
            		if(cell.getStringCellValue().contains("支付表编号")){
            			continue;
            		}else{
            			num++;
            		}
            		if("".equals(paySchCds)){
            			paySchCds =  "'" + cell.getStringCellValue() + "'";
            		}else{
            			paySchCds += ",'" + cell.getStringCellValue() + "'";
            		}
            	}
            }
            if(num <= 999){
            	arr.add(paySchCds);
    			paySchCds = "";
    			num = 0;
            }
		 } catch (IOException e) {
	        	result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
				BaseLogUtils.error(logger, "parseExcel", "错误[Exception] -ERROR:" +e.getMessage(), CurrentThreadContext.getCurrentUserName());
				e.getStackTrace();
	          
	        }  
	        result.setData(arr);
	        return result; 
	}
	
	/**
	 * 到权证名称弹出列表页面
	 */
	@RequestMapping(value = "/toCompListPage.do", method = { RequestMethod.GET })
	public ModelAndView toPublicCompListPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("archive/warrantFileManage/archiveChooseList");
		String multiRow = request.getParameter("multiRow");
		view.addObject("multiRow", multiRow);
		String sysCd = CurrentThreadContext.getCurrentSysCd(); 
		String orgCd = CurrentThreadContext.getCurrentOrgCd();
		//权证类别
		request.setAttribute("warrantTypeList", arcBscInfoService.getKvList(sysCd, orgCd, ArchiveConstants.ARC001));
		BaseLogUtils.info(logger, "toPublicCompListPage", "跳转到权证名称弹出列表页面", CurrentThreadContext.getCurrentUserName());
		return view;
	}
	
	/**
	 * 初始化档案资料下载列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initListDownload.do")
	@ResponseBody
	public Object initListDownload(ArcMgrMainQC qc,HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String searchName = request.getParameter("demo.name");
//		支付表组
		String paySchCds = request.getParameter("paySchCds");
//		资产名称组
		String searchCodeGrpCd = request.getParameter("searchCodeGrpCd");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		if (StringUtils.isNotEmpty(paySchCds) ||StringUtils.isNotEmpty(searchCodeGrpCd) ) {
			qc.setCrtUsrName("("+paySchCds+")");//使用用户名存放支付表组
			qc.setArcReceiptName("("+searchCodeGrpCd+")");//资产包名组
		}
//		if(qc.getCstMgrOrgCd() != null && qc.getCstMgrOrgCd().length()>12){//省公司编码长度
//			qc.setCstMgrOrgCd(qc.getCstMgrOrgCd().substring(0,12));
//		}
		page.setCondition(qc);
		//TODO SOMETHING
		Pager pager = this.warrantFileManageMService.selectListForDownListPage(page);
		List<ArcMgrMainVO> list = (List<ArcMgrMainVO>) pager.getResultList();
		ListPageVO<ArcMgrMainVO> listPage = new ListPageVO<ArcMgrMainVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}
	/**
	 * 获取下载路径
	 * @param request
	 * @param response
	 * @return
	 * @throws BaseException
	 */
	@RequestMapping(value = "/getPath.do", method = {RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public DataResultVO getPath(HttpServletRequest request, HttpServletResponse response)throws BaseException{
		BaseLogUtils.info(logger, "getPath", "进入下载文件方法");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		String contractNo = request.getParameter("contractNo");
		if(StringUtils.isEmpty(contractNo)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("参数为空");
		}
		FilSignDTO dto = new FilSignDTO();
		dto.setContractNo(contractNo);
		FilSignDTO resuDto = this.filSignService.downLoad(dto);
		if(resuDto != null && StringUtils.isNotEmpty(resuDto.getFilePath())){
			result.setInfo(resuDto.getFilePath());
			return result;
		}else{
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("下载文件失败");
			BaseLogUtils.info(logger, "getPath", "下载失败");
			return result;
		}
	}
	
	 
	/**
	 * 单条数据下载档案资料信息
	 * @throws FileNotFoundException 
	 */
	@RequestMapping(value = "/downLoadOne.do")
	@ResponseBody
	public Object downLoadOne(HttpServletRequest request,HttpServletResponse response) throws FileNotFoundException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES);
		String contractNo = request.getParameter("contractNo");// 合同号
		String paySchNo1 = request.getParameter("paySchNo");//支付表号
		String fileName_ = request.getParameter("fileName");//权证名称
		SimpleDateFormat dt222 = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
		String filePath1 = "uploadQZ/";
		String serverFilePath = this.getServerFilePath(filePath1);
    	System.out.println("serverFilePath="+serverFilePath);
    	SimpleDateFormat dt = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
    	Calendar cal = Calendar.getInstance();
    	String cdate = dt.format(cal.getTime()); 
		int flag = 0;
		//根据合同号和支付表号查找档案信息id
		if("".equals(paySchNo1)){//无下载项
			result.setSuccess(BaseConstant.IS_YESNO_NO);
		}else{
			ArcMgrDetailQC qc=new ArcMgrDetailQC();
			qc.setContractNo(contractNo);
			qc.setPaylistCode(paySchNo1);
			qc.setFileName("("+fileName_+")");//权证名称组;
			//查询档案资料（id
			BaseLogUtils.info(logger, "downLoadOne", "=======查询档案资料开始===========");
			List<ArcMgrDetailDTO> arcMgrDetailDTOList = this.warrantFileManageMService.searchArchiveList(qc);
			//2018-12-14
			List<ArcMgrDetailVO> arcMgrDetailVOList=  ArcMgrDetailVOTransform.toVOList(arcMgrDetailDTOList);
			this.arcMgrMainService.getFiles(arcMgrDetailVOList);
			BaseLogUtils.info(logger, "downLoadOne", "=======查询档案资料结束,arcMgrDetailDTOList.size()="+arcMgrDetailVOList.size());
			if(arcMgrDetailVOList != null && arcMgrDetailVOList.size() > 0){//档案资料
				for(int i=0;i<arcMgrDetailVOList.size();i++){
					String paySchNo = arcMgrDetailVOList.get(i).getPaylistCode()!=null?arcMgrDetailVOList.get(i).getPaylistCode().toString():"";//档案资料中是否有支付表号-确定存储路径
					String fNm = arcMgrDetailVOList.get(i).getFileName().toString();//权证名称
					SysUlFilesRecQueryCondition condition = new SysUlFilesRecQueryCondition();//文件
//					设置公共属性
					condition.setPkId(arcMgrDetailVOList.get(i).getId().toString());
					//！！！系统代码，上传功能未实现，此处暂用11000测试！！！！
					condition.setSysCd(CurrentThreadContext.getCurrentSysCd());
					BaseLogUtils.info(logger, "downLoadOne", "查询扫描件集合" , "PkId="+condition.getPkId()+"SysCd="+condition.getSysCd());
					List<SysUlFilesRecVO> filesList = this.sysUlFilesRecService.searchList(condition);//扫描件集合
					//2018-12-14
					ArcMgrDetailVO dvo = arcMgrDetailVOList.get(i);
					//获取附件-承租人(权证类别2)-身份证-客户id-权证资料-商业险	-项目id-权证资料-设备销售发票-prj_prd_dtl
					if ("1".equals(dvo.getUlFlag())&&dvo.getUlFiles() !=null && !"".equals(dvo.getUlFiles().toString()) )
					{
						if (dvo.getUlFiles()!=null&&dvo.getUlFiles().size()>0) {
							List<SysUlFilesRecVO> list2 =dvo.getUlFiles();
							for(int jj=0;jj<list2.size();jj++){
								SysUlFilesRecVO filet = new SysUlFilesRecVO();
								String filePath =list2.get(jj).getFilePath();
								filet.setFileNm(filePath.substring(filePath.lastIndexOf("/")+1));
						        filet.setFilePath(filePath);
						        filet.setAbsLocPath(list2.get(jj).getAbsLocPath());
						        filesList.add(filet);
						        BaseLogUtils.info(logger, "downLoad", "FileOutputStream" , "参数："+filet);
						    }
						}
					}
					//合同电子赋值--电子合同
					if (ArchiveConstants.DOSSOER_TEMP_3.equals(arcMgrDetailVOList.get(i).getDossierTemp()) &&arcMgrDetailVOList.get(i).getEleId()!=null)
					{
						//电子合同和征信系统查询授权书RC_CST_BSC_INFO身份证号匹配
						FilSignQueryCondition qc3=new FilSignQueryCondition();
						qc3.setId(dvo.getEleId());
						List<FilSignDTO> list2=this.filSignApiService.getListFilSignByQc(qc3);if (list2!=null&&list2.size()>0) {
							SysUlFilesRecVO filet = new SysUlFilesRecVO();
							String filePath =list2.get(0).getFilePath();
							filet.setFileNm(filePath.substring(filePath.lastIndexOf("/")+1));
					        filet.setFilePath(filePath);
					        filet.setAbsLocPath(list2.get(0).getAbsLocPath());
					        filesList.add(filet);
					        BaseLogUtils.info(logger, "downLoad", "FileOutputStream" , "参数："+filet);
						}
						
					}
					if(CollectionUtils.isNotEmpty(filesList) && filesList.size()>0){
						flag=flag+1;
						for(int jj=0;jj<filesList.size();jj++){//循环下载
							SysUlFilesRecVO file = filesList.get(jj);
							if(filesList.get(jj)!=null && filesList.get(jj).getAbsLocPath() != null){
						        String fileName = file.getFileNm();//request.getParameter("fileName");
						        String filePath = file.getFilePath();//request.getParameter("filePath");
						        String filePathlo = file.getAbsLocPath();
						        OutputStream os =null;
						        FileInputStream fis =null;
						        try {
						        	 
								    BaseLogUtils.info(logger, "downLoadOne", "filePath=" , filePath);
								    //BaseLogUtils.info(logger, "downLoadOne", "filePath=" , filePath);
								    //BaseLogUtils.info(logger, "downLoadOne", "FileOutputStream" , "参数："+serverFilePath+contractNo+"/"+paySchNo+"/"+fNm+"/"+file.getFileNm());
//						        	File f = new File(serverFilePath+cdate.toString()+"/"+contractNo+"/"+paySchNo+"/"+fNm+"/");
						        	// 构造URL 
						        	File f;
						        	if("".equals(paySchNo)){
						        		f = new File(serverFilePath+cdate.toString()+"/"+contractNo+"/"+fNm+"/");
						        	}else{
						        		f = new File(serverFilePath+cdate.toString()+"/"+contractNo+"/"+paySchNo+"/"+fNm+"/");
						        	}
						        	 fis = new FileInputStream(filePathlo!=null?filePathlo:filePath);
						        	// 创建文件夹
							        if (!f.exists()) {
							            f.mkdirs();
							        }
							        // 1K的数据缓冲    
							        byte[] bs = new byte[1024];    
							        // 读取到的数据长度    
								   // BaseLogUtils.info(logger, "downLoadOne", "FileOutputStream" , "参数："+serverFilePath+contractNo+"/"+paySchNo+"/"+fNm+"/"+file.getFileNm());
								   // BaseLogUtils.info(logger, "downLoadOne", "FileOutputStream" , "参数："+f.getPath()+"/"+file.getFileNm());
							        // 输出的文件流     
							         os = new FileOutputStream(f.getPath()+"/"+file.getFileNm()); 
							        int bytesRead;
				                    while (-1 != (bytesRead = fis.read(bs, 0, bs.length))) {
				                        os.write(bs, 0, bytesRead);
				                    }
							        // 完毕，关闭所有链接    
							        os.close();   
							        os=null;
							        fis.close();
			                        fis = null;
							        
						        } catch (BaseException ex) {
						            result.setSuccess(BaseConstant.IS_YESNO_NO);
						            result.setInfo(ex.getMessage());
						            BaseLogUtils.info(logger, "downLoadOne", "文件下载失败.FILENAME:" + fileName + ".FILEPATH:" + filePath + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
						            
						            // return result;
						        } catch (Exception ex) {
						            result.setSuccess(BaseConstant.IS_YESNO_NO);
						            result.setInfo("文件下载失败!");
						            BaseLogUtils.error(logger, "downLoadOne", "文件下载失败,系统错误.FILENAME:" + fileName + ".FILEPATH:" + filePath + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
						            
						            // return result;
						        }finally{
						        	try{
						                if(os!=null){
						                    os.close();
						                }
						                if(fis!=null){
						                    fis.close();
						                }
						            }
						            catch(IOException ex){
						                ex.printStackTrace();
						            }
						        }
							}
						
						}
					}
				}
			}
		}
		if(flag == 0){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("文件下载失败,没有下载项！");
		}else{
			//保存完文件夹后，打成压缩包
			int flagys = 0;
	        String uuid = UUID.randomUUID().toString().replace("-", "");
	        String currentTime = DateUtils.formatDateToString(new Date(), DateUtils.YYYYMMDD);
	        String tmpZipFileName = uuid+currentTime + ".zip";//临时名称
	        String	serverFilePath11 = serverFilePath+tmpZipFileName;
	        String serverPath = serverFilePath11.replace(PropertiesCacheUtils.getProperty(SysUlFilesRecConstant.SYS_FILE_UPLOAD_ROOT_PATH), PropertiesCacheUtils.getProperty(SysUlFilesRecConstant.SYS_FILE_UPLOAD_SERVER_PATH));
	    	//							       
			FileOutputStream fos1 = new FileOutputStream(new File(serverFilePath11));//保存路径为全路径
			BaseLogUtils.info(logger, "downLoadOne", "准备调用压缩方法"+serverPath);
			flagys =toZip(serverFilePath+cdate.toString()+"/", fos1,true);
			if(flagys == 0){
				BaseLogUtils.info(logger, "downLoadOne", "压缩方法失败！");
				result.setSuccess(BaseConstant.IS_YESNO_NO);
			}else{
				BaseLogUtils.info(logger, "downLoadOne", "文件根路径.serverFilePath:"+serverFilePath11);
				BaseLogUtils.info(logger, "downLoadOne", "返回服务器路径.serverPath:"+serverPath);
	            result.setInfo(serverPath);
	            result.setData(serverPath);
	            result.setSuccess(BaseConstant.IS_YESNO_YES);
			}
	        
		}
		return result;
	}
	
	/**
	 * 压缩成ZIP 方法1
	 * @param srcDir 压缩文件夹路径 
	 * @param out    压缩文件输出流
	 * @param KeepDirStructure  是否保留原来的目录结构,true:保留目录结构; 
	 * 							false:所有文件跑到压缩包根目录下(注意：不保留目录结构可能会出现同名文件,会压缩失败)
	 * @throws RuntimeException 压缩失败会抛出运行时异常
	 */
	public int toZip(String srcDir, OutputStream out, boolean KeepDirStructure)
			throws RuntimeException{
		int flag= 1;
		long start = System.currentTimeMillis();
		ZipOutputStream zos = null ;
		try {
			zos = new ZipOutputStream(out);
			File sourceFile = new File(srcDir);
			compress(sourceFile,zos,sourceFile.getName(),KeepDirStructure);
			long end = System.currentTimeMillis();
			System.out.println("压缩完成，耗时：" + (end - start) +" ms");
			BaseLogUtils.info(logger, "toZip-压缩完成，耗时：" + (end - start) +" ms", "");
		} catch (Exception e) {
			flag = 0;
			BaseLogUtils.info(logger, "toZip-压缩失败！", "");
			throw new RuntimeException("zip error from ZipUtils",e);
		}finally{
			if(zos != null){
				try {
					zos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return flag;
	}
	/**
	 * 递归压缩方法
	 * @param sourceFile 源文件
	 * @param zos		 zip输出流
	 * @param name		 压缩后的名称
	 * @param KeepDirStructure  是否保留原来的目录结构,true:保留目录结构; 
	 * 							false:所有文件跑到压缩包根目录下(注意：不保留目录结构可能会出现同名文件,会压缩失败)
	 * @throws Exception
	 */
	private static void compress(File sourceFile, ZipOutputStream zos, String name,boolean KeepDirStructure) throws Exception{
		byte[] buf = new byte[1024*10];
		if(sourceFile.isFile()){
			// 向zip输出流中添加一个zip实体，构造器中name为zip实体的文件的名字
			zos.putNextEntry(new ZipEntry(name));
			// copy文件到zip输出流中
			int len;
			FileInputStream in = new FileInputStream(sourceFile);
			while ((len = in.read(buf)) != -1){
				zos.write(buf, 0, len);
			}
			// Complete the entry
			zos.closeEntry();
			in.close();
		} else {
			File[] listFiles = sourceFile.listFiles();
			if(listFiles == null || listFiles.length == 0){
				// 需要保留原来的文件结构时,需要对空文件夹进行处理
				if(KeepDirStructure){
					// 空文件夹的处理
					zos.putNextEntry(new ZipEntry(name + "/"));
					// 没有文件，不需要文件的copy
					zos.closeEntry();
				}
				
			}else {
				for (File file : listFiles) {
					// 判断是否需要保留原来的文件结构
					if (KeepDirStructure) {
						// 注意：file.getName()前面需要带上父文件夹的名字加一斜杠,
						// 不然最后压缩包中就不能保留原来的文件结构,即：所有文件都跑到压缩包根目录下了
						compress(file, zos, name + "/" + file.getName(),KeepDirStructure);
					} else {
						compress(file, zos, file.getName(),KeepDirStructure);
					}
					
				}
			}
		}
	}	


	
	
	/**
	 * 创建文件服务器保存路径
	 */
	private String getServerFilePath(String filePath)throws BaseException{
		String prifixPath = PropertiesCacheUtils.getProperty(SysUlFilesRecConstant.SYS_FILE_UPLOAD_ROOT_PATH);//根目录
		StringBuffer savePath = new StringBuffer(prifixPath);//最终保存路径
		if(!savePath.toString().endsWith(SysUlFilesRecConstant.SYS_FILE_PATH_SLASH)){//判断是否以"/"结尾,不是加入斜杠
    		savePath.append(SysUlFilesRecConstant.SYS_FILE_PATH_SLASH);
    	}
		savePath.append(PropertiesCacheUtils.getProperty(SysUlFilesRecConstant.UPLOAD_COSTOMER_PATH));//自定义代码-其中包括系统代码
		if(StringUtils.isNotEmpty(filePath)){//如果不等于空则加入
			if(filePath.startsWith(SysUlFilesRecConstant.SYS_FILE_PATH_SLASH)){//判断是否以"/"开头
				savePath.append(filePath.substring(1));
			}else{
				savePath.append(filePath);
			}
			
		}
		if(!savePath.toString().endsWith(SysUlFilesRecConstant.SYS_FILE_PATH_SLASH)){//判断是否以"/"结尾
    		savePath.append(SysUlFilesRecConstant.SYS_FILE_PATH_SLASH);
    	}
		String currentTime = cn.cmm.base.framework.utils.DateUtils.formatDateToString(new Date(), cn.cmm.base.framework.utils.DateUtils.YYYYMMDD);
		savePath.append(currentTime);
		savePath.append(SysUlFilesRecConstant.SYS_FILE_PATH_SLASH);
	    //检查目录
		File pathFile = new File(savePath.toString());
	    if (!pathFile.exists()) {
	    	BaseLogUtils.info(logger,"getServerFilePath","文件保存服务器路径不存在需要创建.savePath:"+savePath);
	    	//文件夹不存 创建文件
	    	boolean createPath = pathFile.mkdirs();
	    	if(!createPath){
	    		BaseLogUtils.info(logger,"getServerFilePath","创建文件保存服务器路径失败.savePath:"+savePath);
	    		throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "服务器附件目录未创建成功!");
	    	}
	    	BaseLogUtils.info(logger,"getServerFilePath","创建文件保存服务器路径成功.savePath:"+savePath);
	    }
	    BaseLogUtils.info(logger,"getServerFilePath","获取文件保存服务器路径.savePath:"+savePath);
	    return savePath.toString();
	}
	
	/**
	 * 下载信息
	 * @throws FileNotFoundException 
	 */
	@RequestMapping(value = "/downLoad.do")
	@ResponseBody
	public Object downLoad(HttpServletRequest request,HttpServletResponse response) throws FileNotFoundException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES);
//		String contractNos = request.getParameter("contractNos");//合同号
		String paySchNos = request.getParameter("paySchNos");//支付表号
		String fileName_ = request.getParameter("fileName");//权证名称
		String filePath1 = "uploadQZ/";
		String serverFilePath = this.getServerFilePath(filePath1);
    	System.out.println("serverFilePath="+serverFilePath);
    	SimpleDateFormat dt = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
    	Calendar cal = Calendar.getInstance();
    	String cdate = dt.format(cal.getTime()); 
    	String uuid = UUID.randomUUID().toString().replace("-", "");
	    String currentTime = DateUtils.formatDateToString(new Date(), DateUtils.YYYYMMDD);
	    String tmpZipFileName = uuid+currentTime + ".zip";//临时名称
		int flag=0;//是否有下载项
		try {
			BaseLogUtils.info(logger, "downLoad", "===============批量下载开始！,支付表组：" + paySchNos);
			//支付表号List集合
			List<String> pkIdsList = new ArrayList<String>();
			if((StringUtils.isNotEmpty(paySchNos))){
				JSONArray paySchNosArray = JSONArray.fromObject(paySchNos);
				for (Object object : paySchNosArray) {
					pkIdsList.add(object.toString().trim());
				}
			}
			BaseLogUtils.info(logger, "downLoad", "==========批量下载,pkIdsList.size()：" + pkIdsList.size());
			//批量下载-按照合同号-支付表号-权证名称进行存储
			if(pkIdsList != null && pkIdsList.size() > 0){//支付表号为空则提示，未选择下载数据
				ArcMgrDetailQC qc=new ArcMgrDetailQC();
				for(int k=0;k<pkIdsList.size();k++){
					qc.setContractNo(pkIdsList.get(k).substring(1,pkIdsList.get(k).length()-3));//设置合同号
					String notNullPaylistNo=pkIdsList.get(k).substring(1,pkIdsList.get(k).length()-1); 
					qc.setPaylistCode(notNullPaylistNo);//设置支付表号
					qc.setFileName("("+fileName_+")");//权证名称组;
					//查询档案资料
					List<ArcMgrDetailDTO> arcMgrDetailDTOList = this.warrantFileManageMService.searchArchiveList(qc);
					//2018-12-14
					List<ArcMgrDetailVO> arcMgrDetailVOList=  ArcMgrDetailVOTransform.toVOList(arcMgrDetailDTOList);
					this.arcMgrMainService.getFiles(arcMgrDetailVOList);
					BaseLogUtils.info(logger, "downLoad", "该支付表号"+pkIdsList.get(k).substring(1,pkIdsList.get(k).length()-1)+"合同和支付表档案资料份数=" + arcMgrDetailVOList.size());
					if(arcMgrDetailVOList != null && arcMgrDetailVOList.size() > 0){//档案资料
						for(int i=0;i<arcMgrDetailVOList.size();i++){
							String contractNo = arcMgrDetailVOList.get(i).getContractNo()!=null?arcMgrDetailVOList.get(i).getContractNo().toString():pkIdsList.get(k).substring(1,pkIdsList.get(k).length()-3);// 合同号
							String paySchNo = arcMgrDetailVOList.get(i).getPaylistCode()!=null?arcMgrDetailVOList.get(i).getPaylistCode().toString():"";//档案资料中是否有支付表号-确定存储路径
							String fNm = arcMgrDetailVOList.get(i).getFileName().toString();//权证名称
							BaseLogUtils.info(logger, "downLoad", "fNm="+fNm);
							SysUlFilesRecQueryCondition condition = new SysUlFilesRecQueryCondition();//文件
	//							设置公共属性
							condition.setPkId(arcMgrDetailVOList.get(i).getId().toString());
	//				            condition.setTabNm(ArchiveConstants.FILE_ARC_MGR_DETAIL);
					        condition.setSysCd(CurrentThreadContext.getCurrentSysCd());
					        BaseLogUtils.info(logger, "downLoad", "=========查询扫描件集合PkId="+condition.getPkId()+"SysCd="+condition.getSysCd());
							List<SysUlFilesRecVO> filesList = this.sysUlFilesRecService.searchList(condition);//扫描件集合
							//2018-12-14
							ArcMgrDetailVO dvo = arcMgrDetailVOList.get(i);
							//获取附件-承租人(权证类别2)-身份证-客户id-权证资料-商业险	-项目id-权证资料-设备销售发票-prj_prd_dtl
							if ("1".equals(dvo.getUlFlag())&&dvo.getUlFiles() !=null && !"".equals(dvo.getUlFiles().toString()) )
							{
								if (dvo.getUlFiles()!=null&&dvo.getUlFiles().size()>0) {
									List<SysUlFilesRecVO> list2 =dvo.getUlFiles();
									for(int jj=0;jj<list2.size();jj++){
										SysUlFilesRecVO filet = new SysUlFilesRecVO();
										String filePath =list2.get(jj).getFilePath();
										filet.setFileNm(filePath.substring(filePath.lastIndexOf("/")+1));
								        filet.setFilePath(filePath);
								        filet.setAbsLocPath(list2.get(jj).getAbsLocPath());
								        filesList.add(filet);
								        BaseLogUtils.info(logger, "downLoad", "FileOutputStream" , "参数："+filet);
								    }
								}
							}
							//合同电子赋值--电子合同
							if (ArchiveConstants.DOSSOER_TEMP_3.equals(arcMgrDetailVOList.get(i).getDossierTemp()) &&arcMgrDetailVOList.get(i).getEleId()!=null)
							{
								//电子合同和征信系统查询授权书RC_CST_BSC_INFO身份证号匹配
								FilSignQueryCondition qc3=new FilSignQueryCondition();
								qc3.setId(dvo.getEleId());
								List<FilSignDTO> list2=this.filSignApiService.getListFilSignByQc(qc3);if (list2!=null&&list2.size()>0) {
									SysUlFilesRecVO filet = new SysUlFilesRecVO();
									String filePath =list2.get(0).getFilePath();
									filet.setFileNm(filePath.substring(filePath.lastIndexOf("/")+1));
							        filet.setFilePath(filePath);
							        filet.setAbsLocPath(list2.get(0).getAbsLocPath());
							        filesList.add(filet);
							        BaseLogUtils.info(logger, "downLoad", "FileOutputStream" , "参数："+filet);
								}
								
							}
							if(CollectionUtils.isNotEmpty(filesList) && filesList.size()>0){
								flag=flag+1;
								for(int jj=0;jj<filesList.size();jj++){//循环下载
									if(filesList.get(jj)!=null && filesList.get(jj).getFilePath() != null){
										SysUlFilesRecVO file = filesList.get(jj);
								        String fileName = file.getFileNm();//request.getParameter("fileName");
								        String filePath = file.getFilePath();//request.getParameter("filePath");
								        String filePathlo = file.getAbsLocPath();
								        try {
								        	BaseLogUtils.info(logger, "downLoad", "filePathlo=" , filePathlo);
								        	BaseLogUtils.info(logger, "downLoad", "filePath=" , filePath);
								        	BaseLogUtils.info(logger, "downLoad", "serverFilePath+cdate.toString()/contractNo/paySchNo/fNm/)=" , serverFilePath+cdate.toString()+"/"+contractNo+"/"+paySchNo+"/"+fNm+"/");
								        	// 构造URL 
								        	File f;
								        	if("".equals(paySchNo)){
								        		f = new File(serverFilePath+cdate.toString()+"/"+contractNo+"/"+fNm+"/");
								        	}else{
								        		f = new File(serverFilePath+cdate.toString()+"/"+contractNo+"/"+paySchNo+"/"+fNm+"/");
								        	}
								        	// 创建文件夹
									        if (!f.exists()) {
									            f.mkdirs();
									        }
									        // 输入流    
									        FileInputStream fis =  new FileInputStream(filePathlo!=null?filePathlo:filePath);
									        // 1K的数据缓冲    
									        byte[] bs = new byte[1024];    
									        // 读取到的数据长度    
										    BaseLogUtils.info(logger, "downLoad", "FileOutputStream" , "参数："+serverFilePath+contractNo+"/"+paySchNo+"/"+fNm+"/"+file.getFileNm());
										    BaseLogUtils.info(logger, "downLoad", "FileOutputStream" , "参数："+f.getPath()+"/"+file.getFileNm());
										    // 输出的文件流     
									        OutputStream os = new FileOutputStream(f.getPath()+"/"+file.getFileNm()); 
									        int bytesRead;
						                    while (-1 != (bytesRead = fis.read(bs, 0, bs.length))) {
						                        os.write(bs, 0, bytesRead);
						                    }
									        // 完毕，关闭所有链接    
									        os.close();   
									        os=null;
									        fis.close();
					                        fis = null;
									     
								        } catch (BaseException ex) {
								            result.setSuccess(BaseConstant.IS_YESNO_NO);
								            result.setInfo(ex.getMessage());
								            BaseLogUtils.info(logger, "downLoad", "文件下载失败.FILENAME:" + fileName + ".FILEPATH:" + filePath + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
								            //return result;
								        } catch (Exception ex) {
								            result.setSuccess(BaseConstant.IS_YESNO_NO);
								            result.setInfo("文件下载失败!");
								            BaseLogUtils.error(logger, "downLoad", "文件下载失败,系统错误.FILENAME:" + fileName + ".FILEPATH:" + filePath + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
								            //return result;
								        }
									}
								}
							}
						}
					}
				}
			
			}
			}catch (Exception e) {
 			BaseLogUtils.error(logger, "downLoad", "批量下载错误:" + e.getMessage());
 			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_700, BaseExceptionConstant.BASE_EXCEPTION_CODE_700_NAME+e.getMessage());
 		}
		if(flag == 0){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("文件下载失败,没有下载项！");
		}else{
			 //保存完文件夹后，打成压缩包
			int flagys = 0;
	        String	serverFilePath11 = serverFilePath+tmpZipFileName;
	        String serverPath = serverFilePath11.replace(PropertiesCacheUtils.getProperty(SysUlFilesRecConstant.SYS_FILE_UPLOAD_ROOT_PATH), PropertiesCacheUtils.getProperty(SysUlFilesRecConstant.SYS_FILE_UPLOAD_SERVER_PATH));
		    FileOutputStream fos1 = new FileOutputStream(new File(serverFilePath11));//保存路径为全路径
		    BaseLogUtils.info(logger, "downLoad", "准备调用压缩方法"+serverPath);
		    flagys =toZip(serverFilePath+cdate.toString()+"/", fos1,true);
			if(flagys == 0){
				BaseLogUtils.info(logger, "downLoad", "压缩方法失败！");
				result.setSuccess(BaseConstant.IS_YESNO_NO);
			}else{
				BaseLogUtils.info(logger, "downLoad", "文件根路径.serverFilePath:"+serverFilePath11);
				BaseLogUtils.info(logger, "downLoad", "返回服务器路径.serverPath:"+serverPath);
	            result.setInfo(serverPath);
	            result.setData(serverPath);
	            result.setSuccess(BaseConstant.IS_YESNO_YES);
			}
		}
		return result;
	}

	
	/**
	 * 获取附件保存路径,不带最后一个文件名称的路径
	 * @param modelName
	 * @return
	 */
	private String getFileSavePath(String modelName){
		String prifixPath = PropertiesCacheUtils.getProperty(UploadConstant.UPLOAD_ROOT_PATH);//根目录
		System.out.println("根目录prifixPath="+prifixPath);
		StringBuffer savePath = new StringBuffer(prifixPath);//最终保存路径
		if(!savePath.toString().endsWith(SysUlFilesRecConstant.SYS_FILE_PATH_SLASH)){//判断是否以"/"结尾,不是加入斜杠
    		savePath.append(SysUlFilesRecConstant.SYS_FILE_PATH_SLASH);
    	}
		savePath.append(PropertiesCacheUtils.getProperty(UploadConstant.UPLOAD_COSTOMER_PATH));//自定义代码-其中包括系统代码
		if(StringUtils.isNotEmpty(modelName)){//如果不等于空则加入
			if(modelName.startsWith(SysUlFilesRecConstant.SYS_FILE_PATH_SLASH)){//判断是否以"/"开头
				savePath.append(modelName.substring(1));
			}else{
				savePath.append(modelName);
			}
		}
		if(!savePath.toString().endsWith(SysUlFilesRecConstant.SYS_FILE_PATH_SLASH)){//判断是否以"/"结尾
    		savePath.append(SysUlFilesRecConstant.SYS_FILE_PATH_SLASH);
    	}
		String currentTime = DateUtils.formatDateToString(new Date(), DateUtils.YYYYMMDD);
		savePath.append(currentTime);
		savePath.append(SysUlFilesRecConstant.SYS_FILE_PATH_SLASH);
	    //检查目录
	    File pathFile = new File(savePath.toString());
	    if (!pathFile.exists()) {
	    	//文件夹不存 创建文件
	    	boolean createPath = pathFile.mkdirs();
	    	if(!createPath){
	    		throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "服务器附件目录未创建成功!"+savePath.toString());
	    	}
	    }
	    return savePath.toString();
	}
	
	/**
	 * 档案归档超期提醒列表
	 */
	@RequestMapping(value = "/toListPageOverdue.do", method = { RequestMethod.GET})
	public String toListPageOverdue(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String sysCd = CurrentThreadContext.getCurrentSysCd(); 
		String orgCd = CurrentThreadContext.getCurrentOrgCd();
		//获取归档状态
		request.setAttribute("archiveStateList", arcMgrMainService.getStorageStatusList());
		//事业部
		List<KeyValueVO> orgList = this.cstBscInfoService
						.searchBusinessOrgList();
		request.setAttribute("buOrgCdList", orgList);
		//省公司
		request.setAttribute("prList", arcMgrMainService.getPrList());
		
		BaseLogUtils.info(logger, "toListPageOverdue", "跳转到档案归档超期提醒列表页面.", CurrentThreadContext.getCurrentUserName());
		return "archive/warrantFileManage/warrantArchiveOverdue";
	}
	/**
	 * 初始化档案归档超期提醒列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initListOverdue.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initListOverdue(ArcMgrMainQC qc,HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String searchName = request.getParameter("demo.name");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		if (StringUtils.isNotEmpty(searchName)) {
			//TODO SOMTHING
		}
//		if(qc.getCstMgrOrgCd() != null && qc.getCstMgrOrgCd().length()>12){//省公司编码长度
//			qc.setCstMgrOrgCd(qc.getCstMgrOrgCd().substring(0,12));
//		}
		page.setCondition(qc);

		//TODO SOMETHING
		Pager pager = this.warrantFileManageMService.selectListForListPage(page);
		List<ArcMgrMainVO> list = (List<ArcMgrMainVO>) pager.getResultList();
		ListPageVO<ArcMgrMainVO> listPage = new ListPageVO<ArcMgrMainVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initListOverdue", "档案归档超期提醒查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 查询档案基础信息列表数据
	 */
	@RequestMapping("/initArchiveList.do")
	@ResponseBody
	public Object initArchiveList(ArcMgrDetailQC qc,HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String contractNo = request.getParameter("contractNo");//合同号
		String paylistCode = request.getParameter("paySchNo");//支付表号
		String fileName1 = request.getParameter("fileName");//权证名称
		
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}
		qc.setContractNo(contractNo);
		qc.setPaylistCode(paylistCode);
		qc.setFileName("("+fileName1+")");
		List<ArcMgrDetailDTO> arcMgrDetailDTOList = this.warrantFileManageMService.searchArchiveList(qc);
		List<ArcMgrDetailVO> arcMgrDetailVOList = ArcMgrDetailVOTransform.toVOList(arcMgrDetailDTOList);
		try{
			for(int i=0;i<arcMgrDetailVOList.size();i++){
				ArcMgrDetailVO arcMgrDetailVOList_=arcMgrDetailVOList.get(i);
				if(arcMgrDetailVOList_.getEleId()!=null){
					SysUlFilesRecQueryCondition condition = new SysUlFilesRecQueryCondition();//文件
					//设置公共属性
					condition.setPkId(arcMgrDetailVOList_.getEleId().toString());
					//系统代码
				    condition.setSysCd("11000");
				    List<SysUlFilesRecVO> filesList = this.sysUlFilesRecService.searchList(condition);//扫描件集合
					if(CollectionUtils.isNotEmpty(filesList) && filesList.size()>0){
						for(int jj=0;jj<filesList.size();jj++){//下载
						    arcMgrDetailVOList_.setFilePath(filesList.get(0).getFilePath());
							arcMgrDetailVOList_.setArcLevelNm(filesList.get(0).getFileNm());
						}
					}
				}
				//合同电子赋值--电子合同
					if (ArchiveConstants.DOSSOER_TEMP_3.equals(arcMgrDetailVOList_.getDossierTemp()) &&arcMgrDetailVOList_.getEleId()!=null)
					{
						//电子合同和征信系统查询授权书RC_CST_BSC_INFO身份证号匹配
						FilSignQueryCondition qc3=new FilSignQueryCondition();
						qc3.setId(arcMgrDetailVOList_.getEleId());
						BaseLogUtils.info(logger, "initArchiveList", "访问电子合同接口参数.", "模板id："+arcMgrDetailVOList_.getEleContract()+" EleId："+arcMgrDetailVOList_.getEleId());
						List<FilSignDTO> list2=this.filSignApiService.getListFilSignByQc(qc3);//根据合同号和合同名称查出电子合同id等
						if (list2!=null&&list2.size()>0) {
							arcMgrDetailVOList_.setEleId(null);
							arcMgrDetailVOList_.setFilePath(list2.get(0).getFilePath());
							arcMgrDetailVOList_.setArcLevelNm(list2.get(0).getContractNm());
							BaseLogUtils.info(logger, "downLoad", "FileOutputStream" , "参数："+arcMgrDetailVOList_);
						}
					}
			}
			//2018-12-14
			//获取附件-承租人(权证类别2)-身份证-客户id-权证资料-商业险	-项目id-权证资料-设备销售发票-prj_prd_dtl	
			 this.arcMgrMainService.getFiles(arcMgrDetailVOList);
		} catch (BaseException ex) {
			BaseLogUtils.error(logger, "initArchiveList", "查询档案基础信息列表数据.", CurrentThreadContext.getCurrentUserName(), ex);
			logger.error(ex.getMessage(), ex);
		} catch (Exception ex) {
			BaseLogUtils.error(logger, "initArchiveList", "查询档案基础信息列表数据", CurrentThreadContext.getCurrentUserName(), ex);
			logger.error("获取数据失败！", ex);
		}
		BaseLogUtils.info(logger, "initArchiveList", "查询档案基础信息列表数据.", CurrentThreadContext.getCurrentUserName());
		return new ListPageVO<ArcMgrDetailVO>(arcMgrDetailVOList, arcMgrDetailVOList.size());
	}

	/**
	 * 借阅超期提醒列表
	 */
	@RequestMapping(value = "/toListPageBorrowOverdue.do", method = { RequestMethod.GET})
	public String toListPageBorrowOverdue(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String sysCd = CurrentThreadContext.getCurrentSysCd(); 
		String orgCd = CurrentThreadContext.getCurrentOrgCd();
		//事业部
		List<KeyValueVO> orgList = this.cstBscInfoService
						.searchBusinessOrgList();
		request.setAttribute("buOrgCdList", orgList);
		//省公司
		request.setAttribute("prList", arcMgrMainService.getPrList());
		
		BaseLogUtils.info(logger, "toListPageBorrowOverdue", "跳转到借阅超期提醒列表页面.", CurrentThreadContext.getCurrentUserName());
		return "archive/warrantFileManage/warrantBorrowOverdue";
	}
	/**
	 * 初始化借阅超期提醒列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initListBorrowOverdue.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initListBorrowOverdue(ArcMgrMainQC qc,HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String searchName = request.getParameter("demo.name");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		if (StringUtils.isNotEmpty(searchName)) {
			//TODO SOMTHING
		}
		page.setCondition(qc);
		Pager pager = this.warrantFileManageMService.selectBorrowOverdueListPage(page);
		List<ArcMgrMainVO> list = (List<ArcMgrMainVO>) pager.getResultList();
		ListPageVO<ArcMgrMainVO> listPage = new ListPageVO<ArcMgrMainVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initListBorrowOverdue", "借阅超期提醒查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}
	

		//TODO SOMETHING
//		Pager pager = this.warrantFileManageMService.selectListForListPage(page);
	
	/**
	 * 档案超期提醒导出支付表信息
	 */
	@RequestMapping("/exportPayToExcel.do")
	@ResponseBody
	public Object exportPayToExcel(ArcMgrMainQC q,HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_BK_EXPORT_SUCC);
		String eFlag = request.getParameter("eFlag");//导出标识
		if(StringUtils.isEmpty(eFlag)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_PARAM_IS_BAD);
			BaseLogUtils.info(logger, "exportPayToExcel", "导出数据,参数不完整.[eFlag="+eFlag+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
//		List<ArcMgrDetailVO> clist=new ArrayList<ArcMgrDetailVO>();//合同类权证
//		List<ArcMgrDetailVO> dlist=new ArrayList<ArcMgrDetailVO>();//支付表类权证
		try {
			BaseLogUtils.info(logger, "exportPayInfo", "eFlag:"+eFlag, CurrentThreadContext.getCurrentUserName());
			//根据条件查询导出支付表和合同号信息
			List<ArcMgrMainDTO> listma = this.warrantFileManageMService.selectListForListPageToexcle(q);
			String path = this.warrantFileManageMService.exportPayInfo(q,eFlag);
			if(StringUtils.isNotEmpty(path)){
				result.setSuccess(BaseConstant.IS_YESNO_YES);
				result.setInfo(SysLogConstant.LOG_BK_EXPORT_SUCC);
				result.setData(path);
				BaseLogUtils.info(logger, "exportPayToExcel", "导出归档超期模块数据成功", CurrentThreadContext.getCurrentUserName());
			}
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.error(logger, "exportPayToExcel", "导出归档超期模块数据失败.", CurrentThreadContext.getCurrentUserName(), ex);
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "exportPayToExcel", "导出归档超期模块数据失败,系统错误..", CurrentThreadContext.getCurrentUserName(), ex);
		}
		
		return result;
	}

	/**
	 * 导出借阅超期信息
	 */
	@RequestMapping("/exportBtnEvent.do")
	@ResponseBody
	public Object exportBtnEvent(ArcMgrMainQC qc,HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_BK_EXPORT_SUCC);
		try {
			String path = this.warrantFileManageMService.exportBtnEvent(qc);
			if(StringUtils.isNotEmpty(path)){
				result.setSuccess(BaseConstant.IS_YESNO_YES);
				result.setInfo(SysLogConstant.LOG_BK_EXPORT_SUCC);
				result.setData(path);
				BaseLogUtils.info(logger, "exportPayToExcel", "导出借阅超期模块数据成功", CurrentThreadContext.getCurrentUserName());
			}
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.error(logger, "exportPayToExcel", "导出借阅超期模块数据失败.", CurrentThreadContext.getCurrentUserName(), ex);
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "exportPayToExcel", "导出借阅超期模块数据失败,系统错误..", CurrentThreadContext.getCurrentUserName(), ex);
		}
		
		return result;
	}
	
	/**
	 * 组织机构信息
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/searchOrgTree.do", method = { RequestMethod.GET })
	@ResponseBody
	public Object searchOrgTree(HttpServletRequest request,
			HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES,
				"获取成功");
		String cstMgrOrgCd = request.getParameter("cstMgrOrgCd");// 客户经理ID
		try {
			JSONArray array = new JSONArray();
			Long currentOrgId = CurrentThreadContext.getCurrentOrgId();
			array = this.prjBscInfoService.searchParentAndCurrentAllsOrgTree(
					currentOrgId, cstMgrOrgCd);
			// array =
			// this.sysOrgService.searchOrgTreeByCurrentUser(CurrentThreadContext.getCurrentOrgCd(),
			// CurrentThreadContext.getCurrentSysCd());
			if (null == array) {
				array = new JSONArray();
			}
			result.setData(array);
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			logger.error(ex.getMessage(), ex);
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("获取数据失败！");
			logger.error("获取数据失败！", ex);
		}
		return result;
	}
	
	/**
	 * 组织机构信息
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/searchBuOrgTree.do", method = { RequestMethod.GET })
	@ResponseBody
	public Object searchBuOrgTree(HttpServletRequest request,
			HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES,
				"获取成功");
		String cstMgrOrgCd = request.getParameter("cstMgrOrgCd");// 客户经理ID
		String userId = request.getParameter("userId");
		try {
			JSONArray array = new JSONArray();
			array = this.prjBscInfoService.searchBuParentAndCurrentAllsOrgTree(cstMgrOrgCd,userId);
			if (null == array) {
				array = new JSONArray();
			}
			JSONObject obj = new JSONObject();
            obj.put("ischecked", false);
            obj.put("id", "");
            obj.put("text", "");
            obj.put("pid", "");
            obj.put("orgCd", "");
            obj.put("orgDispNm", "");
            array.add(obj);
			result.setData(array);
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			logger.error(ex.getMessage(), ex);
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("获取数据失败！");
			logger.error("获取数据失败！", ex);
		}
		return result;
	}
	
    /*
     * 打包下载
     */
    @RequestMapping(value = "/zipDownloadByPkId.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView zipDownloadByPkId(HttpServletRequest request, HttpServletResponse response) {
    
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String tmpZipFileName = uuid + ".zip";//临时名称
        try {
            byte[] buffer = new byte[1024];
            ZipOutputStream out = new ZipOutputStream(response.getOutputStream());

            response.setContentType("application/x-msdownload;");
            response.setHeader("Content-Disposition", "attachment; filename=" + tmpZipFileName);
            request.setCharacterEncoding("UTF-8");

//            String data = "[170102164002161,170102164002164]";
            String pkId = request.getParameter("pkId");
        	if(StringUtils.isEmpty(pkId)){
        		throw new Exception("主键为空");
    		}
            SysUlFilesRecQueryCondition condition = new SysUlFilesRecQueryCondition();
            condition.setPkId(pkId);
            condition.setTabNm(ArchiveConstants.FILE_ARC_MGR_DETAIL);
            condition.setSysCd(CurrentThreadContext.getCurrentSysCd());
            List<SysUlFilesRecVO> sysUlFilesRecDTOS = this.sysUlFilesRecService.searchList(condition);
            Map<String, SysUlFilesRecDTO> SysUlFilesRecMap = new HashMap<String, SysUlFilesRecDTO>();
           
            List<String> list = new ArrayList<String>();
            Map<String, Integer> map = new HashMap<String, Integer>();
            for (SysUlFilesRecVO sysUlFilesRecVO: sysUlFilesRecDTOS) {
                String fileName = sysUlFilesRecVO.getDatNm() != null ? sysUlFilesRecVO.getDatNm() : sysUlFilesRecVO.getFileNm();
                String filePath = sysUlFilesRecVO.getFilePath();
                fileName = fileName + filePath.substring(filePath.lastIndexOf("."));
                FileInputStream fis = null;
                try {
                    fis = new FileInputStream(sysUlFilesRecVO.getAbsLocPath());
                    if (list.contains(fileName)) {
                        map.put(fileName, map.get(fileName) + 1);
                        fileName = fileName.replace(".", "(" + map.get(fileName) + ").");
                    } else {
                        map.put(fileName, 0);
                    }
                    out.putNextEntry(new ZipEntry(fileName));
                    //下载的文件名写入list
                    list.add(fileName);
                    int bytesRead;
                    while (-1 != (bytesRead = fis.read(buffer, 0, buffer.length))) {
                        out.write(buffer, 0, bytesRead);
                    }
                } catch (Exception e) {
                    BaseLogUtils.error(logger, "batchDownload", "下载打包文件循环中失败!" + pkId, e);
                } finally {
                    if (null != out) {
                        out.flush();
                        out.closeEntry();
                    }
                    if (null != fis) {
                        fis.close();
                        fis = null;
                    }
                }
            }
            if (null != out) {
                out.finish();
                out.close();
                out = null;
            }
        } catch (Exception e) {
            BaseLogUtils.error(logger, "batchDownload", "下载打包文件失败!", e);
        }
        return null;
    }
    


}

